import { useEffect, useRef, useState } from 'react'
import { useModel } from './useModel'

export const useFormState = <T>(
  value: T,
  validate: (value: T) => [boolean, string]
) => {
  const firstRef = useRef(true)
  const [state, bindState, setState] = useModel(value)
  const [bindStatus, setItemStatus] = useState({
    validateStatus: '' as any,
    help: ''
  })

  // true校验通过 false不通过
  const resolveStatus = () => validate(state)[0]

  useEffect(() => {
    if (firstRef.current) {
      firstRef.current = false
      return
    }

    const [status, message] = validate(state)
    setItemStatus(
      status
        ? {
            validateStatus: 'success',
            help: ''
          }
        : {
          validateStatus: 'error',
          help: message
        }
    )
  }, [state])

  return [state, bindState, resolveStatus, bindStatus, setState] as const
}
